﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Security.Cryptography;
using System.Threading;

namespace rsa_test
{
    public partial class Form1 : Form
    {
        private static string readpublickey = "<RSAKeyValue><Modulus>0OLNSBeCcxsQ7gaPFUI6M36KWQ9PiRl2MF7tx3qw9YxWkvmy8pID7bjGf9vHEbYMv9D2K3pePTkeSGQ3pt4W0tocKiMFomb8fkoNUsVoS/+xBgsE0Le2FmoUnJBhBu7o7Mi+Ue0Fnr8NshcNVINSpNTSdnTapeEosmSfKhjetpE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
        private static string readprivatekey = "<RSAKeyValue><Modulus>0OLNSBeCcxsQ7gaPFUI6M36KWQ9PiRl2MF7tx3qw9YxWkvmy8pID7bjGf9vHEbYMv9D2K3pePTkeSGQ3pt4W0tocKiMFomb8fkoNUsVoS/+xBgsE0Le2FmoUnJBhBu7o7Mi+Ue0Fnr8NshcNVINSpNTSdnTapeEosmSfKhjetpE=</Modulus><Exponent>AQAB</Exponent><P>9mqXKcmJF5RnSAM7GQTQf9L2RujyZb8Q4LgtSv11vhadwodJPXkGk0gir6P13aA91e4tue8k4dw10UZ8xUfNaw==</P><Q>2QKLicWhFr+VxsPOuZbm5ZrZT5IK7mUV9P9zXgJfk7NkuDlL0lbQyE/eIfSqQQ1aHuUO18kwAMoLgnGVRkiu8w==</Q><DP>YCVY09op3oRuBAAWt/1T6PwEUcikg6SYTkYujfr1TPUAGx20KwMk2KSlvAhqb04NsoIbX1f6+RF2AjDRkBwi/w==</DP><DQ>NnC+AsUSgXt0npWWsdZafHVZWO3hUicH2BuRnJ7pzUru1IyDKfRfkjD/H/OaFpG77w41qAqvwTLuqj3GXghz4w==</DQ><InverseQ>1dYl6cdguE1VgUX56eh6eTfGjXia5DcHRj9E6gd3ZjGcpW0PDX2dDFbkeR78fBVynuNgStfE6jaaqFXxPojkLA==</InverseQ><D>FnOKJOmB9+U82JiT4HER2F8Nd60Rm2bFMUXCwOILCxleZMW52iCfk3l8vFle+CRdEnDfRKUOY/4zpww+fwz33tgLH/12+kz8r4czcrvGCWLbPosgFTxqfxmvNNQVukNtAzoGv7n3ActK5xbUCF+Y7d1VjV9AXPw+APEUJZ2oftE=</D></RSAKeyValue>";
        private static RSACryptoServiceProvider crypt;
        private static byte[] bytes;

        public Form1()
        {
            InitializeComponent();
        }
        public static string ToHex(byte[] bytes)
        {
            var sb = new StringBuilder();
            foreach (byte b in bytes)
            {
                sb.Append(b.ToString("X2"));
                sb.Append(' ');
            }
            return sb.ToString();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("加密文字信息不能为空！");
                return;
            }

            try
            {
                crypt = new RSACryptoServiceProvider();
                UTF8Encoding enc = new UTF8Encoding();
                bytes = enc.GetBytes(textBox1.Text);
                crypt.FromXmlString(readpublickey);
                bytes = crypt.Encrypt(bytes, false);
                textBox4.Text = enc.GetString(bytes);
                string encryttext = ToHex(bytes);
                textBox2.Text = "加密结果(十六进制显示)：\n\r" + encryttext + "\n";
            }
            catch
            {
                MessageBox.Show("请检查是否打开公匙或者公匙是否损坏！");

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            try
            {
                UTF8Encoding enc = new UTF8Encoding();
                byte[] decryptbyte;
                string _strtmp=textBox4.Text;
                crypt.FromXmlString(readprivatekey);
                decryptbyte = crypt.Decrypt(bytes, false);
                string decrypttext = enc.GetString(decryptbyte);
                textBox3.Text = "解密结果：\n" + decrypttext + "\n";
            }
            catch
            {
                MessageBox.Show("请检查是否打开私匙或者私匙是否损坏！");

            }
        }
        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="length">目标字符串的长度</param>
        /// <param name="useNum">是否包含数字，1=包含，默认为包含</param>
        /// <param name="useLow">是否包含小写字母，1=包含，默认为包含</param>
        /// <param name="useUpp">是否包含大写字母，1=包含，默认为包含</param>
        /// <param name="useSpe">是否包含特殊字符，1=包含，默认为不包含</param>
        /// <param name="custom">要包含的自定义字符，直接输入要包含的字符列表</param>
        /// <returns>指定长度的随机字符串</returns>
        public string GetRnd(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
        {
            byte[] b = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
            Random r = new Random(BitConverter.ToInt32(b, 0));
            string s = null, str = custom;

            if (useNum == true) { str += "0123456789"; }
            if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
            if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
            if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }

            for (int i = 0; i < length; i++)
            {
                s += str.Substring(r.Next(0, str.Length - 1), 1);
            }

            return s;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Text = GetRnd(8, true, true, true, true, "");
        }
    }
}
